package cn.milolab.djback.service;

import cn.milolab.djback.bean.entity.Employee;
import cn.milolab.djback.conf.DjException;
import cn.milolab.djback.dao.EmployeeDAO;
import cn.milolab.djback.dao.JobRecordDAO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.google.common.base.Preconditions.checkNotNull;
/**
 * @author 叶欣委
 */
@Service
public class EmployeeService {
    @Autowired
    EmployeeDAO employeeDAO;
    @Autowired
    JobRecordDAO jobRecordDAO;

    /**
     * 查看社员
     * @param id
     * @param sort
     * @param page
     * @param limit
     * @return
     */
    public Map<String, Object> getEmployee(Integer id, String sort, Integer page, Integer limit) {
        //注意：此处开启分页一定要在数据库查询之前调用，否则会不起作用
        PageHelper.startPage(page,limit);
        //对获得的员工进行分页
        PageHelper.startPage(page, limit);
        //根据条件获得员工
        List<Employee> employeeList = employeeDAO.getEmployee(sort);
        //如果传过来id的话直接进行过滤
        if (!StringUtils.isEmpty(id)) {
            employeeList.removeIf(employee -> !employee.getId().equals(id));
        }
        //开启分页
        PageInfo<Employee> employees = new PageInfo<>(employeeList);
        //将分页后的结果放入Map中并返回
        HashMap<String, Object> result = new HashMap<>(1);
        result.put("employees", employees.getList());
        return result;
    }

    /**
     * 添加社员
     * @param addEmployee
     * @param userId
     */
    @Transactional(rollbackFor = Exception.class)
    public void addEmployee(Employee addEmployee, Integer userId) {
        checkNotNull(addEmployee,"请求参数不能为空");
        checkNotNull(addEmployee.getJobSerial(),"工号不能为空");
        checkNotNull(addEmployee.getStuSerial(),"学号不能为空");
        //通过userId得到employee
        Employee employee = employeeDAO.getEmployeeByUserId(userId);
        checkNotNull(employee,"没有找到该社员");
        //如果角色为空则默认为普通社员
        if (StringUtils.isEmpty(addEmployee.getRole())) {
            addEmployee.setRole(Employee.RoleLevel.EMPLOYEE);
        }
        System.out.println(addEmployee);
        //判断社员是否存在
        Employee employee1 = employeeDAO.getEmployeeBySerial(addEmployee.getStuSerial(),addEmployee.getJobSerial());
        if (!StringUtils.isEmpty(employee1)) {
            throw DjException.internalServerError("社员已经存在");
        }
        //判断学号是否存在
        employee1 = employeeDAO.getEmployeeByStuSerial(addEmployee.getStuSerial());
        if (!StringUtils.isEmpty(employee1)) {
           throw DjException.internalServerError("学号已存在");
        }
        //判断工号是否存在
        employee1 = employeeDAO.getEmployeeByJobSerial(addEmployee.getJobSerial());
        if (!StringUtils.isEmpty(employee1)) {
            throw DjException.internalServerError("工号已存在");
        }
        //判断权限是否足够
        if (employee.getRole().getLevel() <= addEmployee.getRole().getLevel()) {
            throw DjException.accessDenied("权限不足");
        } else {
            try {
                employeeDAO.insertEmployee(addEmployee);
            } catch (Exception e) {
                throw DjException.internalServerError("添加社员失败");
            }
        }
    }

    /**
     * 修改员工信息
     * @param updateEmployee
     * @param userId
     */
    public void updateEmployee(Employee updateEmployee, Integer userId) {
        checkNotNull(updateEmployee,"更改信息不能为空");
        checkNotNull(userId,"参数不能为空");
        //通过userId获得employee
        Employee employee = employeeDAO.getEmployeeByUserId(userId);
        //比较查看是否权限足够
        if (employee.getRole().getLevel() < updateEmployee.getRole().getLevel()) {
            throw DjException.accessDenied("权限不足");
        } else {
            try {
                employeeDAO.updateEmployee(updateEmployee);
            } catch (Exception e) {
                throw DjException.internalServerError("修改失败");
            }
        }
    }

    /**
     * 删除社员
     * @param id
     * @param userId
     */
    public void deleteEmployee(Integer id, Integer userId) {
        //通过userId获得employee
        Employee employee = employeeDAO.getEmployeeByUserId(userId);
        //通过id获得要删除的employee
        Employee deleteEmployee = employeeDAO.getEmployeeById(id);
        //判断权限
        if(employee.getRole().ordinal()<=deleteEmployee.getRole().ordinal()){
            throw DjException.accessDenied("权限不足");
        }else{
            try {
                employeeDAO.deleteEmployeeById(id);
            } catch (Exception e) {
                throw DjException.internalServerError("删除社员信息失败");
            }
            try {
                jobRecordDAO.deleteJobRecordByEmployeeId(id);
            } catch (Exception e) {
                throw DjException.internalServerError("删除值班记录失败");
            }
        }
    }
}
